package br.com.componente;

import java.io.IOException;
import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

@FacesComponent("br.com.componente")
public class AlertMessageComponente extends UIComponentBase {

    public static final String COMPONENT_TYPE = "br.com.componente";

    /**
     * constructor for the component.
     */
    public AlertMessageComponente() {
	super();
	setRendererType(null);
    }

    @Override
    public String getFamily() {
	return COMPONENT_TYPE;
    }

    @Override
    public void encodeBegin(FacesContext context) throws IOException {

	Iterator<FacesMessage> iter = context.getMessages();
	// check if there are messages
	if (iter.hasNext()) {

	    System.out.println("existem Mensagens");

	    StringBuffer messages = new StringBuffer();
	    ResponseWriter writer = context.getResponseWriter();
	    // going through all messages
	    while (iter.hasNext()) {
		FacesMessage msg = (FacesMessage) iter.next();
		messages.append(msg.getSummary() + ", ");
	    }
	    // print out the result

	    // writer.write("<h:outputScript>");
	    writer.write("<script> alert('" + messages.toString() + "');</script>");
	    // writer.write("</h:outputScript>");
	} else {
	    ResponseWriter writer = context.getResponseWriter();
	    writer.write("Systema de Mensagens ok");
	}
    }

    @Override
    public void encodeEnd(FacesContext context) throws IOException {
	super.encodeEnd(context);
    }
}
